package people.paper.tv.activity.home.modual.rmrb.view.impl;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.skyworth.util.Util;
import com.skyworth.util.imageloader.ImageLoader;
import com.skyworth.util.imageloader.Transform;
import com.skyworth.util.imageloader.fresco.CoocaaDraweeView;

import people.paper.tv.R;
import people.paper.tv.activity.home.modual.rmrb.view.data.DailyData;

public class DailyImgLayout extends FrameLayout implements View.OnClickListener,
        View.OnFocusChangeListener, View.OnKeyListener {
//    ImageView paper;
    CoocaaDraweeView paper;
    View mFocusView;
    TextView expiredTip;
    RMRBLayout rmrbLayout;
    DailyData.LayoutData layoutData;
    View bigImageView;
    FrameLayout bigLayout;
    String mUrl;
    final int width = Util.Div(790);
    final int height = Util.Div(890);


    float startX;
    float startY;

    public DailyImgLayout(@NonNull Context context) {
        super(context);
        setFocusable(true);
        setFocusableInTouchMode(true);
        setOnClickListener(this);
        setOnFocusChangeListener(this);

        paper = new CoocaaDraweeView(context);
        LayoutParams params = new LayoutParams(width, height);
        addView(paper, params);

        mFocusView = new View(getContext());
        mFocusView.setBackgroundResource(R.mipmap.block_focus);
        int focusW = Util.Div(30) + width;
        int focusH = Util.Div(98) + height;
        LayoutParams focusParams = new LayoutParams(focusW, focusH);
        focusParams.topMargin = Util.Div(-20);
        focusParams.leftMargin = Util.Div(-16);
        addView(mFocusView, focusParams);
        mFocusView.setVisibility(GONE);

        expiredTip = new TextView(context);
        expiredTip.getPaint().setFakeBoldText(true);
        expiredTip.setBackgroundColor(getResources().getColor(R.color.menu_tip_bg));
        expiredTip.setTextSize(Util.Dpi(28));
        expiredTip.setTextColor(getResources().getColor(R.color.title_focus));
        String text = getResources().getString(R.string.former_paper_tip);
        SpannableStringBuilder ssb = new SpannableStringBuilder(text);
        ssb.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.menu_tip_color)), 1, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        expiredTip.setText(ssb);
        expiredTip.setGravity(Gravity.CENTER);
        LayoutParams tipParams = new LayoutParams(LayoutParams.MATCH_PARENT, Util.Div(50));
        tipParams.topMargin = Util.Div(840);
        addView(expiredTip, tipParams);

        bigLayout = new FrameLayout(context);
        bigLayout.setBackgroundColor(getResources().getColor(R.color.title_focus));
        LayoutParams params1 = new LayoutParams(Util.Div(1920), Util.Div(1080));
        params1.leftMargin = -Util.Div(87);
        params1.topMargin = -Util.Div(160);
        addView(bigLayout, params1);
        bigLayout.setFocusable(true);
        bigLayout.setFocusableInTouchMode(true);
        bigLayout.setVisibility(GONE);
        bigLayout.setOnKeyListener(this);
        bigLayout.bringToFront();

        bigImageView = ImageLoader.getLoader().getView(context);
        bigLayout.addView(bigImageView);

//        bigLayout.setClickable(true);
//        bigLayout.setOnTouchListener(new OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return bigTouchEvent(event);
//            }
//        });
    }

    public void setRMRBLayout(RMRBLayout layout) {
        rmrbLayout = layout;
    }

    public void refresh(DailyData.LayoutData layoutData) {
        this.layoutData = layoutData;
        paper.setImageBitmap(null);
        paper.setBackgroundResource(R.drawable.coocaa_logo);
        if(mUrl != null)
            ImageLoader.getLoader().clearCacheFromMemory(mUrl);
        ImageLoader.getLoader().reset(paper);

        mUrl = layoutData.imageUrl;
        ImageLoader.getLoader().with(getContext()).resize(width, height)
                .small(Uri.parse(layoutData.thumbImageUrl))
                .load(Uri.parse(layoutData.imageUrl))
                .transform(new Transform(true){
                    @Override
                    public Bitmap transform(Bitmap dis, Bitmap src)
                    {
                        float dd = (float) width / src.getWidth();

                        Log.i("tag", "rmrb w0:" + dis.getWidth()+"; "+dis.getHeight());

                        dis.setHasAlpha(false);
                        Matrix matrix = new Matrix();
                        matrix.postScale(dd, dd);
                        Canvas canvas = new Canvas(dis);
                        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
                        paint.setFilterBitmap(false);
                        canvas.drawBitmap(src, matrix, paint);
                        Log.i("tag", "rmrb w1:" + dis.getWidth()+"; "+dis.getHeight());
                        return dis;
                    }
                }).into(paper);
    }

    @Override
    public void onClick(View v) {
        setViewFullScreen(true);
    }

    public void setViewFullScreen(boolean isFull) {
        rmrbLayout.setListVisible(!isFull);
        rmrbLayout.isBigPaper = isFull;
        if (isFull) {
            bigLayout.setVisibility(VISIBLE);
            bigLayout.requestFocus();
            bigImageView.scrollTo(0, 0);
            ImageLoader.getLoader().with(getContext()).wrapContent()
                    .setScaleType(ImageView.ScaleType.CENTER_CROP)
                    .small(Uri.parse(layoutData.thumbImageUrl))
                    .load(Uri.parse(layoutData.imageUrl)).into(bigImageView);
            rmrbLayout.addBigPapgerTouchLyt();
        } else {
            this.requestFocus();
            bigLayout.setVisibility(GONE);
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        mFocusView.bringToFront();
        mFocusView.setVisibility(hasFocus ? View.VISIBLE : View.INVISIBLE);
        String text;
        if (hasFocus) {
            text = getResources().getString(R.string.full_paper_tip);
        } else {
            text = getResources().getString(R.string.former_paper_tip);
        }
        SpannableStringBuilder ssb = new SpannableStringBuilder(text);
        ssb.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.menu_tip_color)),
                1, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        expiredTip.setText(ssb);
        Util.focusAnimate(this, hasFocus);
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            Log.i("BigImg", "BigImg getx：" + bigImageView.getScrollX() + "; gety:"
                    + bigImageView.getScrollY() + "; " + bigImageView.getWidth() + "; " + bigImageView.getHeight()
                    + "; " + bigLayout.getWidth() + "; " + bigLayout.getHeight());

            if (keyCode == KeyEvent.KEYCODE_BACK) {
                return rmrbLayout.onKey(v, keyCode, event);
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                if (bigImageView.getScrollX() > 19)
                    bigImageView.scrollBy(-20, 0);
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                if (bigImageView.getScrollX() <= 300)
                    bigImageView.scrollBy(20, 0);
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                if (bigImageView.getScrollY() > 19)
                    bigImageView.scrollBy(0, -20);
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                if (bigImageView.getScrollY() <= 2000)
                    bigImageView.scrollBy(0, 20);
                return true;
            }
        }
        return false;
    }

    public void resume() {
        if(layoutData != null)
            Log.i("tag", "daily resume:" + mUrl+"; "+layoutData.layoutTitle);
        if(rmrbLayout.isBigPaper && layoutData != null)
            ImageLoader.getLoader().with(getContext()).wrapContent()
                    .setScaleType(ImageView.ScaleType.CENTER_CROP)
                    .small(Uri.parse(layoutData.thumbImageUrl))
                    .load(Uri.parse(layoutData.imageUrl)).into(bigImageView);
        else {
            if(layoutData != null)
                refresh(layoutData);
        }
    }

    public void pause() {
        setViewFullScreen(false);
        if(layoutData != null)
            Log.i("tag", "daily pause:" + mUrl+"; "+layoutData.layoutTitle);
        if (paper != null)
            ImageLoader.getLoader().reset(paper);
        if (bigImageView != null)
            ImageLoader.getLoader().reset(bigImageView);
        if(mUrl != null)
            ImageLoader.getLoader().clearCacheFromMemory(mUrl);
    }

    public void destroy() {
        if(layoutData != null)
            Log.i("tag", "daily destroy:" + mUrl+"; "+layoutData.layoutTitle);
        if (paper != null)
            ImageLoader.getLoader().reset(paper);
        if (bigImageView != null)
            ImageLoader.getLoader().reset(bigImageView);
        if(mUrl != null)
            ImageLoader.getLoader().clearCacheFromMemory(mUrl);
    }


    public boolean bigTouchEvent(MotionEvent event){
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                userTouchDown(event);
                break;
//            case MotionEvent.ACTION_MOVE:
//                userTouch(event);
//                break;
            case MotionEvent.ACTION_UP:
                userTouch(event);
                break;

        }
        return true;
    }

    private void userTouchDown(MotionEvent event) {
        startX = event.getRawX();
        startY = event.getRawY();
        //如果两次点击的时间小于一定值，则为双击
//        if (event.getEventTime() - clickTime < DOBLE_CLICK_TIME) {
//            changeSize(startX, startY);
//        }
//        clickTime = event.getEventTime();
    }

    public void userTouch(MotionEvent event) {
        int x = (int)(startX - event.getRawX());
        int y = (int)(startY - event.getRawY());
        if(x < (0 - bigImageView.getScrollX())){
            x = (0 - bigImageView.getScrollX());
        }else if(x > (320 -bigImageView.getScrollX())){
            x = (320 - bigImageView.getScrollX());
        }
        if(y < (0 - bigImageView.getScrollY())){
            y = (0 - bigImageView.getScrollY());
        }else if(y > (2000 -bigImageView.getScrollY())){
            y = (2000 - bigImageView.getScrollY());
        }
        bigImageView.scrollBy(x, y);
    }

    }
